package com.chenhb.watermarkutils;

import java.awt.*;
import java.io.*;
import java.util.Date;

import com.chenhb.watermarkutils.bo.WatermarkBo;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

import javax.swing.*;

/**
 * PDF添加文字水印工具
 *
 * @author 陈海波
 * @date 2021-04-21
 */
public class PdfTextWatermarkUtil extends AbstractWatermark {


    /**
     * PDF添加文字水印
     *
     * @param watermark
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static ByteArrayOutputStream mark(WatermarkBo watermark)
            throws DocumentException, IOException {
        // 要输出的pdf文件
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfReader reader = new PdfReader(new FileInputStream(watermark.getResourceFile()));
        PdfStamper stamper = new PdfStamper(reader, bos);

        // 获取总页数 +1, 下面从1开始遍历
        int total = reader.getNumberOfPages() + 1;
        // 使用classpath下面的字体库
        BaseFont base = BaseFont.createFont(watermark.getFontTtf(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 获取水印文字的高度和宽度
        int textH, textW;
        JLabel label = new JLabel();
        label.setText(watermark.getWatermarkContent());
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        textH = metrics.getHeight();
        textW = metrics.stringWidth(label.getText());

        // 设置水印透明度
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(watermark.getTransparency());
        gs.setStrokeOpacity(watermark.getTransparency());

        Rectangle pageSizeWithRotation;
        PdfContentByte content;
        for (int i = 1; i < total; i++) {
            // 在内容下方加水印
            content = stamper.getUnderContent(i);
            content.saveState();
            content.setGState(gs);

            // 设置字体和字体大小
            content.beginText();
            content.setFontAndSize(base, watermark.getFontSize());
            content.setColorFill(watermark.getColor());
            // 获取每一页的高度、宽度
            pageSizeWithRotation = reader.getPageSizeWithRotation(i);
            float pageHeight = pageSizeWithRotation.getHeight();
            float pageWidth = pageSizeWithRotation.getWidth();
            // 参数顺序分别 中心点、水印内容、X轴偏移、Y轴偏移、旋转角度
            content.showTextAligned(Element.ALIGN_LEFT, watermark.getWatermarkContent(), watermark.getOffsetX() / 1.875f, pageHeight - watermark.getOffsetY() / 1.875f - textH, watermark.getDegree());
            content.endText();
        }
        // 关流
        stamper.close();
        return bos;
    }

}
